/*
 * Copyright 2016 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.elegant.code.validator;

import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.ReflectionUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.lang.reflect.Field;
import java.util.List;

public class OneOfEnumValidator implements ConstraintValidator<OneOfEnum, Integer> {

    private List<Integer> validValues;


    @Override
    public void initialize(OneOfEnum constraintAnnotation) {
        Class<? extends Enum> enumClass = constraintAnnotation.value();
        Enum[] enums = enumClass.getEnumConstants();
        if (enums == null || enums.length <= 0) {
            return;
        }
        validValues = Lists.newArrayList();

        Field field = ReflectionUtils.findField(enumClass, StringUtils.isBlank(constraintAnnotation.field())?"value":constraintAnnotation.field());
        if (field == null) {
            return;
        }
        ReflectionUtils.makeAccessible(field);
        for (Enum oneEnum : enums) {
            validValues.add((Integer) ReflectionUtils.getField(field, oneEnum));
        }
    }

    @Override
    public boolean isValid(Integer value, ConstraintValidatorContext context) {
        return value == null || validValues.contains(value);
    }
}
